﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Windows.Forms;
using Usermanagment.VisualDisplay.UnderTheHood;
using System.Net.Sockets;

namespace Usermanagment.VisualDisplay
{
	public partial class FirstRun : Form
	{
		ServerData serverdata;
		SerializeDat serdat;
		public FirstRun()
		{
			InitializeComponent();
			serverdata = new ServerData();
			serdat = new SerializeDat();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			if (doWork())
			{
				System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadAct));
				t.Start();
				this.Close();
				
			}
		}

		private void ThreadAct()
		{
			Application.Run(new Login(serverdata));
		}

		private Boolean isIpaddress(String address , out String resolve)
		{
			try
			{
				IPAddress add = IPAddress.Parse(address);
				IPAddress[] adds = Dns.GetHostEntry(add).AddressList;
				foreach (IPAddress ip in adds)
				{
					if (ip.AddressFamily.ToString() != ProtocolFamily.InterNetworkV6.ToString())
					{
						resolve = ip + "";						
						return true;
					}
				}
				resolve = "";
				return false;
				
			}
			catch (FormatException e)
			{
				Console.WriteLine("FormatException caught!!!");
				Console.WriteLine("Source : " + e.Source);
				Console.WriteLine("Message : " + e.Message);
				resolve = null;
				return false;
			}
			catch (ArgumentNullException e)
			{
				Console.WriteLine("ArgumentNullException caught!!!");
				Console.WriteLine("Source : " + e.Source);
				Console.WriteLine("Message : " + e.Message);
				resolve = null;
				return false;
			}
			catch (Exception e)
			{
				Console.WriteLine("Exception caught!!!");
				Console.WriteLine("Source : " + e.Source);
				Console.WriteLine("Message : " + e.Message);
				resolve = null;
				return false;
			}
			
		}
		private Boolean isAllOk()
		{
			return ((serverBox.Text.Length > 0) && (userBox.Text.Length > 0) && (passBox.Text.Length > 0) && (dbBox.Text.Length > 0) && (playerdBox.Text.Length > 0) && (statdBox.Text.Length > 0));
		}
		private Boolean fillDetails()
		{
			String t = " ";
			if (isIpaddress(serverBox.Text,out t))
			{
				serverdata.sAddress = t;
				serverdata.sDatabase = dbBox.Text;
				serverdata.sPlayersdb = playerdBox.Text;
				serverdata.sStatsdb = statdBox.Text;
				serverdata.sUser = userBox.Text;
				serverdata.sPassword = passBox.Text;
				return true;
			}
			return false;
		}
		private Boolean doWork()
		{
			if(isAllOk())
				if (fillDetails())
				{
					serdat.work(serverdata);
					return true;
				}
			return false;
			
		}

	}
}
